package com.mooc.ppjoke.ui.login;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import androidx.arch.core.executor.ArchTaskExecutor;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.mooc.lib_common.MyApplication;
import com.mooc.lib_network.ApiResponse;
import com.mooc.lib_network.ApiService;
import com.mooc.lib_network.JsonCallBack;
import com.mooc.lib_network.cache.CacheManager;
import com.mooc.ppjoke.data.User;

/**
 * @ClassName: UserManager$
 * @Description: java类作用描述
 * @Author: 魏靳元
 * @CreateDate: 2022/8/21 18:42
 * @UpdateRemark: 更新内容
 * @Version: 1.0
 */
public class QQUserManager {
    private static final String KEY_CACHE_USER="cache_user";
    private static QQUserManager manager=new QQUserManager();
    private MutableLiveData<User> userMutableLiveData=new MutableLiveData<>();
    private User mUser;
    public static QQUserManager getInstance(){
        return manager;
    }
    private QQUserManager(){
        User cache = (User) CacheManager.getCache(KEY_CACHE_USER);
        if(cache!=null&&cache.getExpires_time()>System.currentTimeMillis()){
            mUser=cache;
        }
    }
    public void saveUser(User user){
        mUser = user;
        CacheManager.saveCache(KEY_CACHE_USER,user);
        if(userMutableLiveData.hasObservers()){
            userMutableLiveData.postValue(user);
        }
    }
    public LiveData<User> login(Context context){
        Intent intent = new Intent(context,LoginActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
        return userMutableLiveData;
    }

    public boolean isLogin(){
        return mUser != null && mUser.getExpires_time()  >  System.currentTimeMillis();
    }

    public User getmUser(){
        return isLogin()?mUser:null;
    }

    public long getUserId(){
        return isLogin()?mUser.getUserId():0;
    }


    public LiveData<User> refresh() {
        if (!isLogin()) {
            return login(MyApplication.getsApplication());
        }
        MutableLiveData<User> liveData = new MutableLiveData<>();
        ApiService.get("/user/query")
                .addParam("userId", getUserId())
                .excute(new JsonCallBack<User>() {
                    @Override
                    public void OnSuccess(ApiResponse<User> response) {
                        saveUser(response.body);
                        liveData.postValue(getmUser());
                    }

                    @SuppressLint("RestrictedApi")
                    @Override
                    public void OnError(ApiResponse<User> response) {
                        ArchTaskExecutor.getMainThreadExecutor().execute(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MyApplication.getsApplication(), response.message, Toast.LENGTH_SHORT).show();
                            }
                        });
                        liveData.postValue(null);
                    }
                });
        return liveData;
    }

//    /**
//     * bugfix:  liveData默认情况下是支持黏性事件的，即之前已经发送了一条消息，当有新的observer注册进来的时候，也会把先前的消息发送给他，
//     * <p>
//     * 就造成了{@linkplain com.mooc.ppjoke.MainActivity#onNavigationItemSelected(MenuItem) }死循环
//     * <p>
//     * 那有两种解决方法
//     * 1.我们在退出登录的时候，把livedata置为空，或者将其内的数据置为null
//     * 2.利用我们改造的stickyLiveData来发送这个登录成功的事件
//     * <p>
//     * 我们选择第一种,把livedata置为空
//     */
    public void logout() {
        CacheManager.delete(KEY_CACHE_USER, mUser);
        mUser = null;
        userMutableLiveData = null;
    }

} 
